import React, { useImperativeHandle, useRef } from 'react';
import { useEffect, useState } from 'react';
import { useModel } from 'umi';
import { Col, Modal, Row } from 'antd';
import type { AudDialogShowParams } from '@/pages/components/Aud/AudDialog';
// import AudDialog from '@/pages/components/Aud/AudDialog';
import Form, { SimpleItem, GroupItem, Label, RequiredRule, RangeRule } from 'devextreme-react/form';
import styles from './style/index.less';
import SetDataGrid from '../../../SetDataGrid';
import { getZCBFDateUpdate, getInfoDateUpdate, zcbfInfoSave, templateListApi, getPeriodInfo, getCloudGroupTemplateList } from '../../service';
// import DateBox from 'devextreme-react/date-box';
import notify from 'devextreme/ui/notify';
import moment from 'moment';
import Popup from 'devextreme-react/popup';
import { changeShowTitleTime, intl } from '@/utils';
// import { TextBox } from 'devextreme-react';
import { DateUpdate, PeriodUpdate } from '../../../SetDataGrid/service';
import SelectBoxCloudDownload from "~/public/cpas-business/components-bs/SelectBoxCloudDownload"
import { deepClone } from '~/public/cpas-business/tools/Tools';

export interface SizeProp {
  width?: number | string,
  height?: number | string,
}

const XMType = window.sessionStorage.electronParams
  ? JSON.parse(window.sessionStorage.electronParams)?.params?.XMType
  : "单机审计项目";

const EditorPop: React.FC<any> = React.forwardRef((props: any, ref) => {
  const { width, height, GridRefresh } = props;

  const { initialState } = useModel('@@initialState');
  const { zcbfid, dbname, ljjxDbName, sjxmbh } = initialState?.curPart as API.CurPart;

  const setDataGridRef = useRef<any>();
  const [visible, setVisible] = useState<boolean>(false);
  const diaParams = useRef<AudDialogShowParams & any>();
  const refsForm = useRef<any>();
  // const [dataGridData, setDataGridData] = useState<any[]>([]);
  const [size, setSize] = useState<SizeProp>({ width, height });
  const [formData, setFormData] = useState<any>({});
  const [cloudGroupTemplate, setCloudGroupTemplate] = useState<any[]>([]);
  const [isShowOpenModal, setIsShowOpenModal] = useState<boolean>(false);
  const selectForm = useRef<any>({});

  // const featData = async () => {
  //   try {
  //     const res = await templateListApi();
  //     setDataGridData(res.data);
  //   } catch (error) {
  //     console.log(error);
  //   }
  // }

  // useEffect(() => {
  //   if (visible) {
  //     featData();
  //   }
  // }, [visible])

  const getCloudGroupData = async () => {
    const res = await getCloudGroupTemplateList({
      dbName: ljjxDbName,
      projectCode: sjxmbh,
      status: 1,
    });
    if (res.success) {
      setCloudGroupTemplate(res.data);
    } else {
      setCloudGroupTemplate([]);
    }
  }

  // 自定义方法
  useImperativeHandle(ref, () => ({
    show: async (params: AudDialogShowParams) => {
      setFormData(params.args.data);
      diaParams.current = params;
      setDataGridRef.current.restYearAllData();
      setDataGridRef.current.restYearTable();
      setVisible(true);
      selectForm.current = {};
      await getCloudGroupData();
    },
    close: () => { setVisible(false) }
  }));

  // 处理日期
  function convertDate(dateString: any) {
    const dateObj = new Date(dateString);
    const year = dateObj.getFullYear();
    const month = String(dateObj.getMonth() + 1).padStart(2, '0');
    const day = String(dateObj.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  }

  const Ok = async () => {
    setDataGridRef.current.saveEditData();
    setTimeout(async () => {
      const yearState = setDataGridRef.current.checkContinuous();
      const checkDuplicateYear = setDataGridRef.current.checkDuplicate();
      const PeriodData = setDataGridRef.current.getPeriodData();
      const EditData = setDataGridRef.current.getData();
      const result: any = refsForm.current.instance.validate();

      if (checkDuplicateYear) {
        notify("年度重复,请您重新修改", 'warning', 2000)
      } else {
        if (yearState) {
          // 左侧from表单接口逻辑
          if (result.isValid) {
            setVisible(false);
            const tempEditData = deepClone(EditData);
            // 设置期间接口逻辑
            tempEditData.forEach((item: any) => {
              item.guid = item.id;
              delete item.id;
              delete item.ByMonth;
            });
            const res = await DateUpdate(dbname, tempEditData);
            await PeriodUpdate(dbname, PeriodData);

            if (res.success) {
              setDataGridRef.current.restYearTable();
              setDataGridRef.current.restYearAllData();
              GridRefresh(true);
            }

            const startTime = moment(formData.AuditReportDate).format('YYYY-MM-DD');
            // 添加 项目库 dbName:dbname,
            const zcbfres = await getZCBFDateUpdate({ ...formData, startTime, zcbfid })
            if (zcbfres) {
              notify('修改成功', 'success', 2000);
              if (diaParams.current?.okCallback) {
                diaParams.current?.okCallback('', '');
              }
            }
            await getPeriodInfo({ dbname, bgType: formData.ReportType });
            if (XMType !== '单机审计项目') {
              const time = convertDate(formData.AuditReportDate);
              // 云平台 接口
              const periodsData = setDataGridRef.current.initData();
              // 类型字段先去掉 后期需要再加
              // reportType: formData.reportType ? formData.reportType : '',
              const r = await zcbfInfoSave({
                // ...data,
                projectCode: sjxmbh,
                receivePerson: formData.ReceivePerson,
                auditReportDate: time,
                auditReportTemplate: formData.AuditReportTemplate,
                dbName: ljjxDbName,
                zcbfID: zcbfid,
                reportType: formData.ReportType,
                periods: periodsData
              })
              console.log(r, 'r----');
            };


          } else {
            const messages = result.brokenRules.map((item: { message: any; }) => item.message);

            const errorMessages = {
              '请选择模板': '请填写报告模板,该内容为必填项',
              '请输入收件人名称': '请填写收件人，该内容为必填项',
              '请选择报告批准报出日期': '请填写报告批准报出日期，该内容为必填项',
            };

            for (const message of messages) {
              if (errorMessages[message]) {
                notify(errorMessages[message], 'error', 2000);
                break;
              }
            }
            // if(message[0]){
            //   notify('请填写收件人,该内容为必填项', "error", 2000);
            // }else if(message[1]){
            //   notify('请填写报告批准报出日期,该内容为必填项', "error", 2000);
            // }
          }

        } else {
          notify("期间年度不连续", 'warning', 2000)
        }
      }
    }, 150)
  }

  // const senderinfores = await getInfoDateUpdate({ ...data })
  // if (senderinfores) notify('修改成功', 'success', 2000);

  // if (diaParams.current?.okCallback) {
  //   diaParams.current?.okCallback('', '')
  // }
  // dbName: string,
  // zcbfID: string,
  // projectCode: string,
  // reportType: string,
  // receivePerson: string,
  // auditReportDate: string,


  const updateAuditReportTemplate = (e: any) => {
    const { selectedItem } = e;
    selectForm.current = selectedItem;
    if (cloudGroupTemplate.length === 0) {
      setFormData((prevState: any) => ({
        ...prevState,
        AuditReportTemplate: selectedItem.tempName,
        ReportType: selectedItem?.reportType ?? ""
      }));
      return;
    }
    const temp1 = cloudGroupTemplate[0];
    if (temp1?.reportType === selectedItem?.reportType) {
      setFormData((prevState: any) => ({
        ...prevState,
        AuditReportTemplate: selectedItem.tempName,
        ReportType: selectedItem?.reportType ?? ""
      }));
    } else {
      setIsShowOpenModal(true);
    }
    return;

  };

  return (
    <>
      <Popup
        ref={ref}
        {...props}
        {...size}
        title={diaParams.current?.args?.title}
        visible={visible}
        minWidth={1100}
        minHeight={480}
        // dragOutsideBoundary={true}
        resizeEnabled={true}
        onResizeEnd={(e) => {
          setSize({ width: e.width, height: e.height });
        }}
        onHiding={() => {
          setVisible(false);
          setDataGridRef.current.restYearAllData();
        }}
        toolbarItems={[
          {
            widget: 'dxButton',
            toolbar: 'bottom',
            location: 'after',
            options: {
              text: intl('pub.cancel', '取消'),
              onClick: () => {
                setVisible(false)
                setDataGridRef.current.restYearAllData();
              },
            },
          },
          {
            widget: 'dxButton',
            toolbar: 'bottom',
            location: 'after',
            options: {
              text: intl('pub.ok', '确定'),
              type: 'default',
              onClick: async () => Ok(),
            },
          },
        ]}
      >
        <div className={styles.dynamicHeight}>
          <Row style={{ height: '100%', }}>
            <Col span={24} className={styles.Form}>
              <div style={{ width: '100%', height: '100%', display: 'flex' }}>
                {/* <DateBox type="date" onValueChanged={(e: any) => {
                  console.log(e);
                }} /> */}
                <div style={{ width: '45%', height: '100%', }}>
                  <div style={{ marginTop: '10px', fontWeight: '600', fontSize: "14px" }}> 基础信息  </div>
                  <div style={{ marginTop: '20px' }}>
                    <Form
                      ref={refsForm}
                      formData={formData}
                      focusStateEnabled={true}
                      showColonAfterLabel={true}
                      alignItemLabels={true}
                    >
                      <GroupItem>
                        <SimpleItem
                          dataField='bsdw'
                          label={{
                            text: '被审计单位',
                            alignment: 'left'
                          }}
                          editorOptions={{
                            // readOnly: true,
                            // showClearButton: true,
                            valueChangeEvent: 'keyup',
                          }}
                          editorType="dxTextBox"
                        >
                          <RequiredRule message="请输入被审计单位" />
                        </SimpleItem>
                        <SimpleItem
                          dataField='shortName'
                          editorOptions={{
                            // readOnly: true,
                            // showClearButton: true,
                            valueChangeEvent: 'keyup',
                          }}
                          label={{ text: '被审计单位简称', alignment: 'left' }}
                          editorType="dxTextBox"
                        >
                          <RequiredRule message="请输入被审计单位简称" />
                        </SimpleItem>
                        <SimpleItem
                          dataField='sjnd'
                          label={{ text: '审计年度', alignment: 'left', }}
                          editorOptions={{
                            readOnly: true,
                            showClearButton: true,
                            valueChangeEvent: 'keyup',
                          }}
                          editorType="dxTextBox"
                        />
                        {/* <SimpleItem
                          dataField='ReportType'
                          label={{
                            text: '报告类型',
                             alignment: 'left',
                            // render: () => LabelTemplate('info')
                          }}

                          editorType="dxSelectBox"
                          editorOptions={{
                            items: [
                              {
                                Type: '上市',
                                id: 0
                              },
                              {
                                Type: '国企',
                                id: 1
                              },
                            ],
                            displayExpr: 'Type',
                            valueExpr: 'Type',
                          }}
                        >
                          <RequiredRule message="请选择报告类型" />
                        </SimpleItem> */}
                        {/* <SimpleItem
                          dataField='AuditReportTemplate'
                          label={{ text: '报告模板', alignment: 'left' }}
                          editorType="dxSelectBox"
                          editorOptions={{
                            items: dataGridData,
                            displayExpr: 'tempName',
                            valueExpr: 'tempName',
                          }}
                        >
                          <RequiredRule message="请选择模板" />
                        </SimpleItem> */}
                        <SimpleItem label={{ text: "报告模板", alignment: "left" }}>
                          <SelectBoxCloudDownload
                            value={formData?.AuditReportTemplate ?? ""}
                            onSelectionChanged={updateAuditReportTemplate}
                          ></SelectBoxCloudDownload>
                        </SimpleItem>
                        <SimpleItem
                          dataField='ReportType'
                          editorType="dxTextBox"
                          label={{ text: '报告类型', alignment: 'left' }}
                          editorOptions={{
                            readOnly: true,
                            valueChangeEvent: 'keyup',
                          }}
                        />
                        <SimpleItem
                          dataField='ReceivePerson'
                          editorType="dxTextBox"
                          label={{ text: '收件人', alignment: 'left' }}
                        >
                          <RequiredRule message="请输入收件人名称" />
                        </SimpleItem>
                        <SimpleItem
                          dataField='AuditReportDate'
                          label={{ text: '报告批准报出日期', alignment: 'left' }}
                          editorType="dxDateBox"
                        >
                          <RequiredRule message="请选择报告批准报出日期" />
                        </SimpleItem>
                      </GroupItem>
                    </Form>
                  </div>
                </div>
                <div style={{ width: '52%', height: '93%', display: 'flex', justifyContent: 'center', marginLeft: "35px" }}>
                  <SetDataGrid ref={setDataGridRef} zcbfPartInfo={diaParams.current?.args?.data} width='100%' height='83%' button={true} />
                </div>
              </div>
            </Col>
          </Row>
        </div>
      </Popup>


      <Popup
        title={'提示信息'}
        visible={isShowOpenModal}
        width={600}
        height={180}
        onHiding={() => {
          selectForm.current = {};
          setIsShowOpenModal(false);
        }}
        toolbarItems={[
          {
            widget: 'dxButton',
            toolbar: 'bottom',
            location: 'after',
            options: {
              text: intl('pub.cancel', '否'),
              onClick: () => {
                selectForm.current = {};
                setIsShowOpenModal(false);
              },
            },
          },
          {
            widget: 'dxButton',
            toolbar: 'bottom',
            location: 'after',
            options: {
              text: intl('pub.ok', '是'),
              type: 'default',
              onClick: async () => {
                setFormData((prevState: any) => ({
                  ...prevState,
                  AuditReportTemplate: selectForm.current.tempName,
                  ReportType: selectForm.current?.reportType ?? ""
                }));
                setIsShowOpenModal(false);
              },
            },
          },
        ]}
      >
        集团合并报告模板为：【{cloudGroupTemplate[0]?.templateName ?? "-暂无-"}】，如果更换模板将导致单体数据无法上传至合并系统，请确认是否更换模板？
      </Popup>
    </>
  );
});

export default EditorPop